package common.gateway.demo04.predicate;

import common.gateway.demo04.predicate.entity.QueryIncludeData;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 判断请求url query 是否包含指定的key
 *
 * @author lihh
 */
@Component
public class QueryIncludeRoutePredicateFactory extends AbstractRoutePredicateFactory<QueryIncludeData> {
  
  @Override
  public List<String> shortcutFieldOrder() {
    // 构建 别名
    return Arrays.asList("key");
  }
  
  public QueryIncludeRoutePredicateFactory() {
    super(QueryIncludeData.class);
  }
  
  @Override
  public Predicate<ServerWebExchange> apply(QueryIncludeData config) {
    return new Predicate<ServerWebExchange>() {
      @Override
      public boolean test(ServerWebExchange serverWebExchange) {
        // 拿到 request 以及 url params
        ServerHttpRequest request = serverWebExchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        
        if (queryParams.isEmpty()) return false;
        return queryParams.containsKey(config.getKey());
      }
    };
  }
}
